﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sac.PiLink;
using System.Configuration;
using System.Data;
using Sac.Data;

namespace Sac.Web
{
    public class CustomTags
    {
        OledbPro oledb;
        string piServer;
        string piUserName;
        string piPassword;
        string db2ConnStr;
        
        public CustomTags()
        {
            piServer = ConfigurationManager.AppSettings["piserver"].ToString();
            piUserName = ConfigurationManager.AppSettings["piuser"].ToString();
            piPassword = ConfigurationManager.AppSettings["pipwd"].ToString();
            db2ConnStr = ConfigurationManager.AppSettings["access"].ToString();
            PIAppLink.ConnectToServer(piServer, piUserName, piPassword);
            oledb = new OledbPro(db2ConnStr);
        }

        /// <summary>
        /// 检查PI数据库中是否存在指定的ID点
        /// </summary>
        /// <param name="tagId">指定的PI数据库中ID点号</param>
        /// <returns>是否存在</returns>
        public bool CheckTag(string tagId)
        {
            bool isExist = false;
            int pointNumber = 0;
            PIAppLink.ConnectToServer(piServer, piUserName, piPassword);
            int errNo= PIAppLink.FindPointNum(tagId, out pointNumber);
            if (errNo == 0)
                isExist = true;
            return isExist;
        }

        /// <summary>
        /// 向关系数据库中插入自定义测点数据
        /// </summary>
        /// <param name="tagId">PI数据库中ID点号</param>
        /// <param name="tagDesc">对该点号添加的描述</param>
        /// <returns>插入数据是否成功</returns>
        public bool InsertTag(string tagId, string tagDesc)
        {
            bool isSuccess = false;
            //如果测点在PI数据库中不存在返回错误信息
            if (!CheckTag(tagId))
                return false;
            string insertSQL = "insert into customtags(tagid,tagdesc) values ('" + tagId + "','" + tagDesc + "')";
            int i = oledb.ExecuteNonQuery(insertSQL);
            if (i > 0)
                isSuccess = true;
            return isSuccess;
        }

        /// <summary>
        /// 根据ID_KEY更新数据库中自定义测点信息
        /// </summary>
        /// <param name="id_key">数据在数据库中的关键字</param>
        /// <param name="tagId">更新的测点在PI数据库中的ID点号</param>
        /// <param name="tagDesc">更新的测点的描述</param>
        /// <returns>更新是否成功</returns>
        public bool UpdateTag(string id_key,string tagId, string tagDesc)
        {
            bool isSuccess = false;
            //如果测点在PI数据库中不存在返回错误信息
            if (!CheckTag(tagId))
                return false;
            string updateSQL = "update customtags set tagid='" + tagId + "',tagdesc='" + tagDesc + "' where id_key=" + id_key;
            int i = oledb.ExecuteNonQuery(updateSQL);
            if (i > 0)
                isSuccess = true;
            return isSuccess;
        }

        /// <summary>
        /// 根据ID_KEY删除数据库中自定义测点信息
        /// </summary>
        /// <param name="id_key">测点信息在关系数据库中的关键字</param>
        /// <returns>返回删除是否成功</returns>
        public bool DeleteTag(string id_key)
        {
            bool isSuccess = false;
            string deleteSQL = "delete from customtags where id_key=" + id_key;
            int i = oledb.ExecuteNonQuery(deleteSQL);
            if (i > 0)
                isSuccess = true;
            return isSuccess;
        }

        /// <summary>
        /// 获取数据库中所有的测点信息
        /// </summary>
        /// <returns>返回包含测点信息的DataTable对象</returns>
        public DataTable GetAllTags()
        {
            string selectSQL = "select * from customtags order by id_key desc";
            return oledb.GetDataTable(selectSQL);
        }

        /// <summary>
        /// 根据描述返回包含该描述的所有测点信息
        /// </summary>
        /// <param name="tagDesc">指定的测点描述</param>
        /// <returns>返回包含测点信息的DataTable对象</returns>
        public DataTable GetTagsByDesc(string tagDesc)
        {
            string selectSQL = "select * from customtags where tagdesc like '%" + tagDesc + "%'";
            DataTable dtTagList = oledb.GetDataTable(selectSQL);
            return dtTagList;
        }

        /// <summary>
        /// 根据描述返回包含该描述的所有测点信息
        /// </summary>
        /// <param name="tagDesc">指定的测点描述</param>
        /// <returns>返回包含测点信息的List集合对象</returns>
        public List<PiTag> GetTagListByDesc(string tagDesc)
        {
            List<PiTag> tagList = new List<PiTag>();
            string selectSQL = "select * from customtags where tagdesc like '%" + tagDesc + "%'";
            DataTable dtTagList = oledb.GetDataTable(selectSQL);
            for (int i = 0; i < dtTagList.Rows.Count; i++)
            {
                PiTag pi = new PiTag();
                pi.Id_Key = int.Parse(dtTagList.Rows[i]["ID_KEY"].ToString());
                pi.TagId = dtTagList.Rows[i]["TAGID"].ToString();
                pi.TagDesc = dtTagList.Rows[i]["TAGDESC"].ToString();
                tagList.Add(pi);
            }
            return tagList;
        }

        /// <summary>
        /// 根据指定的PI数据库中测点的ID号获取关系数据库中自定义测点的信息
        /// </summary>
        /// <param name="tagId">指定的PI数据库中测点ID</param>
        /// <returns>返回包含测点信息的PiTag对象</returns>
        public PiTag GetTagByID(string tagId)
        {
            PiTag tag = new PiTag();
            string selectSQL = "select * from customtags where id_key=" + tagId;
            DataRow drTag = oledb.GetDataRow(selectSQL);
            tag.Id_Key = int.Parse(tagId);
            tag.TagId = drTag["TAGID"].ToString();
            tag.TagDesc = drTag["TAGDESC"].ToString();
            return tag;
        }

        /// <summary>
        /// 获取指定点号，指定时间段内所有PI的值及其对应的时间
        /// </summary>
        /// <param name="tagId">指定的PI点号</param>
        /// <param name="startTime">指定的开始时间</param>
        /// <param name="endTime">指定的结束时间</param>
        /// <returns>包含所有点信息的List集合对象</returns>
        public List<PiValue> GetTagValueByIDAndTime(string tagId, DateTime startTime, DateTime endTime)
        {
            List<PiValue> valueList = new List<PiValue>();
            double[] values;
            DateTime[] valuesTime;
            int count=0;
            PIAppLink.ConnectToServer(piServer, piUserName, piPassword);
            int[] iErrNo = PIAppLink.GetInsideValues(tagId, startTime, endTime, out values, out valuesTime);
            for (int i = 0; i < count; i++)
            {
                PiValue valueItem = new PiValue();
                valueItem.ErrNo = iErrNo[i];
                valueItem.TagValue = values[i];
                valueItem.TagTime = valuesTime[i];
                valueList.Add(valueItem);
            }
            return valueList;
        }

        /// <summary>
        /// 获取指定点号24小时内指定时间间隔的值
        /// </summary>
        /// <param name="tagId">指定点号</param>
        /// <returns>返回包含数据和时间的值</returns>
        public List<PiValue> GetTagValueLatest24(string tagId,int intervalMinute)
        {
            List<PiValue> valueList = new List<PiValue>();
            DateTime startTime = DateTime.Now.AddDays(-1);
            int subMinute = startTime.Minute % intervalMinute;
            startTime.AddMinutes(-subMinute);
            while (startTime <= DateTime.Now)
            {
                DateTime time = startTime;
                double drval = 0;
                PIAppLink.ConnectToServer(piServer, piUserName, piPassword);
                int errNo = PIAppLink.GetPreviousOrAssignValue(tagId, out drval, ref time);
                PiValue pi = new PiValue();
                pi.ErrNo = errNo;
                pi.TagTime = startTime;
                pi.TagValue = drval;
                valueList.Add(pi);
                startTime = startTime.AddMinutes(intervalMinute);
            }
            return valueList;
        }
    }
}
